package com.alibaba.product.service.impl;

import com.alibaba.basic.uitl.BaiduAuditUtils;
import com.alibaba.basic.uitl.DistanceUtil;
import com.alibaba.basic.uitl.LoginContext;
import com.alibaba.basic.uitl.Point;
import com.alibaba.org.domain.Shop;
import com.alibaba.org.mapper.ShopMapper;
import com.alibaba.product.domain.ProductMsg;
import com.alibaba.product.domain.ProductOnlineAuditLog;
import com.alibaba.product.dto.PorductMsgDto;
import com.alibaba.product.mapper.ProductMapper;
import com.alibaba.product.mapper.ProductMsgMapper;
import com.alibaba.product.mapper.ProductOnlineAuditLogMapper;
import com.alibaba.product.service.IProductMsgService;
import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.user.domain.Logininfo;
import com.alibaba.user.domain.User;
import com.alibaba.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2023-03-18
 */
@Service
public class ProductMsgServiceImpl extends BaseServiceImpl<ProductMsg> implements IProductMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ProductOnlineAuditLogMapper logMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private ProductMsgMapper msgMapper;

    @Override
    public void publish(PorductMsgDto dto) {
        // 校验参数
        // 将数据存入数据库
        ProductMsg msg = new ProductMsg();
        BeanUtils.copyProperties(dto,msg);
        msg.setState(0);
        // 调用工具类 去拿到我们拦截里登录人的信息
        Logininfo logininfo = LoginContext.getLogininfo();
        User user = userMapper.findByPhone(logininfo.getPhone());
        msg.setUserId(user.getId());
        super.add(msg);
        // 百度AI审核
        if (!BaiduAuditUtils.TextCensor(dto.getName())){
            ProductOnlineAuditLog log = new ProductOnlineAuditLog();
            log.setAuditId(-1L);
            log.setAuditTime(new Date());
            log.setState(0);
            log.setNote("名字不得行哟乖乖");
            logMapper.add(log);
            return;
        } else {
            // 50公里有没有店铺
            Point point = DistanceUtil.getPoint(dto.getAddress());
            List<Shop> shops = shopMapper.findAll();
            Shop nearestShop = DistanceUtil.getNearestShop(point, shops);
            if(null != nearestShop){
                // 将寻主消息分配给这个店铺 就是给msg的shopId赋值
                msg.setShopId(nearestShop.getId());
            }

        }
        super.update(msg);
    }

    /**
     *  id 是 msg id
     * @param id
     */
    @Override
    public void reject(Long id) {
        // 直接修改shopid 为null
        msgMapper.updateById(id);

    }
}
